<template>
  <ContentWrap class="chem-record-wrap">
    <!-- 标题和添加一行按钮 -->
    <div class="chem-header"> 第{{ formData.samplingPeriod }}天采样 </div>
    <!-- 头部信息表单 -->
    <el-form :model="form" class="chem-form" label-width="90px">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="采样日期">
            <el-date-picker
              v-model="form.sampleDate"
              placeholder="请从气象记录中添加"
              disabled
              style="width: 100%"
              type="date"
              value-format="YYYY-MM-DD"
              @change="emitChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="气压">
            <div class="input-with-unit">
              <el-input v-model="form.airPressure" placeholder="请输入气压" @change="emitChange" />
              <span class="unit-text">kPa</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收集器种类">
            <el-input v-model="form.collectorType" placeholder="请输入" @change="emitChange" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检测类别">
            <el-input v-model="form.type" placeholder="请输入" @change="emitChange" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="检测项目">
            <el-input v-model="form.item" placeholder="检测项目" @change="emitChange" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采样仪器信息">
            <el-input
              v-model="form.samplingInstrumentInfo"
              placeholder="请从列表中选择采样设备"
              @change="emitChange"
              readonly
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采样依据">
            <el-input v-model="form.basis" placeholder="请输入采样依据" @change="emitChange" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="流量计信息">
            <el-input
              :model-value="flowmeterInfoDisplay"
              placeholder="双击选择流量计"
              readonly
              @dblclick="openFlowmeterDialog"
              @change="emitChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 表格 -->
    <el-table :data="form.table" border class="chem-table" stripe>
      <el-table-column align="center" label="采样编号" prop="sampleNo" width="220">
        <template #default="{ row }">
          <el-input v-model="row.sampleNo" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="工作场所" prop="workplace">
        <template #default="{ row }">
          <el-input v-model="row.workplace" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="检测岗位" prop="detectionPost">
        <template #default="{ row }">
          <el-input v-model="row.detectionPost" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" :label="label" prop="sampleObjectLocationed">
        <template #default="{ row, $index }">
          <el-select
            :model-value="getSingleSelect(row.sampleObjectLocation)"
            placeholder="请选择"
            allow-create
            filterable
            clearable
            @update:model-value="(val) => setSingleSelect(row, val)"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in getSampleObjectLocationOptions($index)"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="采样设备编号" prop="samplingEquipmentNo" width="140">
        <template #default="{ row, $index }">
          <el-input
            v-model="row.samplingEquipmentNo"
            placeholder="双击选择采样设备"
            readonly
            @dblclick="openFacilityDialog($index)"
            @change="emitChange"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="采样起止时间" width="180">
        <template #default="{ row }">
          <el-time-picker
            v-model="row.timeRange"
            end-placeholder="结束时间"
            format="HH:mm"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            style="width: auto"
            value-format="HH:mm"
            @change="() => handleTimeRangeChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="采样流量(L/min)">
        <el-table-column align="center" label="采样前" prop="flowBefore" width="55">
          <template #default="{ row }">
            <el-input v-model="row.flowBefore" placeholder="" @change="emitChange" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="采样后" prop="flowAfter" width="55">
          <template #default="{ row }">
            <el-input
              v-model="row.flowAfter"
              placeholder=""
              @change="() => handleFlowAfterChange(row)"
            />
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column align="center" label="采样时长(min)" prop="sampleDuration" width="70">
        <template #default="{ row }">
          <el-input
            v-model="row.sampleDuration"
            placeholder=""
            @input="() => handleSampleDurationChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="采样体积Vt(L)" prop="sampleVolume" width="80">
        <template #default="{ row }">
          <el-input v-model="row.sampleVolume" placeholder="" readonly />
        </template>
      </el-table-column>
      <el-table-column align="center" label="代表接触时间(h)" prop="contactTime" width="70">
        <template #default="{ row }">
          <el-input v-model="row.contactTime" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="采样现场情况记录">
        <el-table-column align="center" label="生产状况" prop="productionStatus" width="60">
          <template #default="{ row }">
            <el-input v-model="row.productionStatus" placeholder="" @change="emitChange" />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="防护设施运行情况"
          prop="protectionFacilityStatus"
          width="80px"
        >
          <template #default="{ row }">
            <el-input v-model="row.protectionFacilityStatus" placeholder="" @change="emitChange" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="防护口罩佩戴情况" prop="maskStatus" width="80px">
          <template #default="{ row }">
            <el-input v-model="row.maskStatus" placeholder="" @change="emitChange" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="气温(℃)" prop="temperature" width="50">
        <template #default="{ row }">
          <el-input v-model="row.temperature" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注(粉尘滤膜编号)" prop="remark" width="80px">
        <template #default="{ row, $index }">
          <el-select
            v-model="row.remark"
            placeholder="请选择"
            clearable
            @change="(val) => handleRemarkChange(val, $index)"
            @focus="
              () => {
                onRemarkFocus($index, row)
                getCllmbhList()
              }
            "
            style="width: 100%"
          >
            <el-option v-for="item in cllmbhList" :key="item" :label="item" :value="item" />
          </el-select>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 设备选择对话框 -->
  <el-dialog
    v-model="facilityDialogVisible"
    append-to-body
    destroy-on-close
    title="选择设备"
    width="60%"
  >
    <div class="dialog-content">
      <Facility
        :default-status="1"
        :instrument-type="instrumentType"
        :show-selection="facilityShowSelection"
        @selection-change="handleFacilitySelectionChange"
        @handle-facility-confirm="handleFacilityConfirm"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="facilityDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleFacilityConfirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch, inject } from 'vue'
import { ElMessage } from 'element-plus'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { useRoute, useRouter } from 'vue-router'
import { ProjectApi } from '@/api/dk/project'
import Facility from '@/views/infra/facility/facility.vue'
// import { FacilityLogApi } from '@/api/infra/facilitylog'

// 新增type和formData prop
const props = defineProps<{
  type: string
  labelName: string
  weatherRecords?: WeatherRecord
  formData?: any
}>()

const emit = defineEmits(['change'])
const facilityDialogVisible = ref(false)
const label = ref('')
const add = ref('')
const remove = ref('')
const instrumentType = ref('')
const cllmbhList = ref([])
const currentRowIndex = ref<number | null>(null)
const selectedFacility = ref<any>(null)
const selectedFlowmeters = ref<any[]>([])
const facilityShowSelection = ref(false)
const facilityDialogContext = ref<{ type: 'table' | 'flowmeter'; rowIndex?: number } | null>(
  null
)
// 记录每一行备注上次选择的值
const previousRemarkMap = ref<Map<number, string>>(new Map())
// 保存完整的选项列表，不会因为用户选择而变化
const originalOptionsMap = ref<Map<number, string[]>>(new Map())

const route = useRoute()
const router = useRouter()
defineOptions({ name: 'HarmfulFactorsRecord' })

// 新增emitChange方法，放在顶部，确保模板可用
const emitChange = () => {
  emit('change', { ...form.value })
}

// 从父组件注入设备可用性校验方法
type CheckEquipmentAvailabilityParams = {
  equipmentId: string
  startTime: string
  endTime: string
  sampleDate: string
  currentLogId?: number | null
  sampleNo?: string
}
const injectedCheckEquipmentAvailability = inject<
  (params: CheckEquipmentAvailabilityParams) => Promise<number | null>
>('checkEquipmentAvailability')

// 计算采样体积：采样后流量 × 采样时长
const calculateSampleVolume = (row: any) => {
  const flowAfter = parseFloat(row.flowAfter) || 0
  const sampleDuration = parseFloat(row.sampleDuration) || 0
  const volume = flowAfter * sampleDuration
  return volume > 0 ? volume.toFixed(2) : ''
}

// 时间计算工具函数
const calculateTimeDifference = (startTime: string, endTime: string): number => {
  if (!startTime || !endTime) return 0

  const start = new Date(`2000-01-01 ${startTime}`)
  const end = new Date(`2000-01-01 ${endTime}`)

  // 如果结束时间小于开始时间，说明跨天了，加24小时
  if (end < start) {
    end.setTime(end.getTime() + 24 * 60 * 60 * 1000)
  }

  const diffMs = end.getTime() - start.getTime()
  return Math.round(diffMs / (1000 * 60)) // 返回分钟数
}

const calculateEndTime = (startTime: string, duration: number): string => {
  if (!startTime || !duration) {
    return ''
  }

  const start = new Date(`2000-01-01 ${startTime}`)
  const end = new Date(start.getTime() + duration * 60 * 1000)

  // 如果跨天了，减去24小时
  if (end.getDate() !== start.getDate()) {
    end.setTime(end.getTime() - 24 * 60 * 60 * 1000)
  }

  return end.toTimeString().slice(0, 5) // 返回HH:mm格式
}

// 处理采样起止时间变化
const handleTimeRangeChange = async (row: any) => {
  const [startTime, endTime] = row.timeRange || ['', '']

  if (startTime && endTime) {
    // 如果起止时间都有值，检查是否是默认的1小时间隔
    const duration = calculateTimeDifference(startTime, endTime)

    // 如果当前有采样时长且计算出的时长是60分钟（1小时），说明是默认行为
    if (row.sampleDuration && duration === 60) {
      // 使用现有的采样时长重新计算结束时间
      const existingDuration = parseInt(row.sampleDuration) || 0
      if (existingDuration > 0 && existingDuration !== 60) {
        const calculatedEndTime = calculateEndTime(startTime, existingDuration)
        row.timeRange = [startTime, calculatedEndTime]

        // 检查设备可用性
        if (row.equipmentId && injectedCheckEquipmentAvailability) {
          const newId = await injectedCheckEquipmentAvailability({
            equipmentId: row.equipmentId,
            startTime,
            endTime: calculatedEndTime,
            sampleDate: form.value.sampleDate,
            currentLogId: row.logId,
            sampleNo: row.sampleNo || ''
          })
          if (newId) row.logId = newId
        }

        emitChange()
        return
      }
    }

    // 正常计算采样时长
    row.sampleDuration = duration.toString()

    // 检查设备可用性
    if (row.equipmentId && injectedCheckEquipmentAvailability) {
      const newId = await injectedCheckEquipmentAvailability({
        equipmentId: row.equipmentId,
        startTime,
        endTime,
        sampleDate: form.value.sampleDate,
        currentLogId: row.logId,
        sampleNo: row.sampleNo || ''
      })
      if (newId) row.logId = newId
    }

    emitChange()
  } else if (startTime && !endTime && row.sampleDuration) {
    // 如果只有开始时间且有采样时长，自动计算结束时间
    const duration = parseInt(row.sampleDuration) || 0
    if (duration > 0) {
      const calculatedEndTime = calculateEndTime(startTime, duration)
      row.timeRange = [startTime, calculatedEndTime]

      // 检查设备可用性
      if (row.equipmentId && injectedCheckEquipmentAvailability) {
        const newId = await injectedCheckEquipmentAvailability({
          equipmentId: row.equipmentId,
          startTime,
          endTime: calculatedEndTime,
          sampleDate: form.value.sampleDate,
          currentLogId: row.logId,
          sampleNo: row.sampleNo || ''
        })
        if (newId) row.logId = newId
      }

      emitChange()
    }
  }
}

// 处理采样时长变化
const handleSampleDurationChange = async (row: any) => {
  const duration = parseInt(row.sampleDuration) || 0
  const [startTime] = row.timeRange || ['', '']

  if (startTime && duration > 0) {
    // 如果有开始时间和采样时长，计算结束时间
    const calculatedEndTime = calculateEndTime(startTime, duration)
    row.timeRange = [startTime, calculatedEndTime]

    // 检查设备可用性
    if (row.equipmentId && injectedCheckEquipmentAvailability) {
      const newId = await injectedCheckEquipmentAvailability({
        equipmentId: row.equipmentId,
        startTime,
        endTime: calculatedEndTime,
        sampleDate: form.value.sampleDate,
        currentLogId: row.logId,
        sampleNo: row.sampleNo || ''
      })
      if (newId) row.logId = newId
    }
  } else if (!startTime && duration > 0) {
    // 如果只有采样时长但没有开始时间，提示用户先选择开始时间
    ElMessage && ElMessage.warning('请先选择开始时间')
  }

  // 计算采样体积
  row.sampleVolume = calculateSampleVolume(row)

  emitChange()
}

// 处理采样后流量变化
const handleFlowAfterChange = (row: any) => {
  // 计算采样体积
  row.sampleVolume = calculateSampleVolume(row)
  emitChange()
}

// 获取sampleObjectLocation选项数组 - 始终返回完整的选项列表
const getSampleObjectLocationOptions = (rowIndex: number) => {
  const tableRow = form.value.table?.[rowIndex]
  let options: string[] = []
  if (tableRow && Array.isArray(tableRow.sampleObjectLocationed)) {
    options = tableRow.sampleObjectLocationed
  } else {
    options = originalOptionsMap.value.get(rowIndex) || []
  }

  if (!tableRow) return options
  const currentWorkplace = tableRow.workplace || ''
  const currentPost = tableRow.detectionPost || ''
  if (!currentWorkplace || !currentPost) return options
  const usedByOthers = new Set<string>()
  form.value.table.forEach((r: any, i: number) => {
    if (
      i !== rowIndex &&
      (r.workplace || '') === currentWorkplace &&
      (r.detectionPost || '') === currentPost
    ) {
      const sel = Array.isArray(r.sampleObjectLocation)
        ? r.sampleObjectLocation[0]
        : r.sampleObjectLocation
      if (sel) usedByOthers.add(sel)
    }
  })
  const currentSelected = Array.isArray(tableRow.sampleObjectLocation)
    ? tableRow.sampleObjectLocation[0]
    : tableRow.sampleObjectLocation
  return options.filter((opt) => !usedByOthers.has(opt) || opt === currentSelected)
}

// 默认按“工作场所+检测岗位”分组，为空选择的行自动分配不冲突的选项
const ensureUniqueDefaultSelection = () => {
  const usedMap = new Map<string, Set<string>>()
  form.value.table.forEach((row: any) => {
    const wp = row.workplace || ''
    const dp = row.detectionPost || ''
    if (!wp || !dp) return
    const key = `${wp}||${dp}`
    if (!usedMap.has(key)) usedMap.set(key, new Set<string>())
    const used = usedMap.get(key)!
    const currentSel = Array.isArray(row.sampleObjectLocation)
      ? row.sampleObjectLocation[0]
      : row.sampleObjectLocation
    if (currentSel) {
      used.add(currentSel)
      return
    }
    const opts: string[] = Array.isArray(row.sampleObjectLocationed)
      ? row.sampleObjectLocationed
      : []
    const pick = opts.find((o) => !used.has(o))
    if (pick) {
      row.sampleObjectLocation = [pick]
      used.add(pick)
    }
  })
}

// 将数组值映射为单选展示值
const getSingleSelect = (val: any) => {
  return Array.isArray(val) ? (val[0] ?? '') : (val ?? '')
}

// 单选更新时写回为数组，保持数据结构一致
const setSingleSelect = (row: any, val: any) => {
  if (val !== '' && val != null) {
    const currentWorkplace = row.workplace || ''
    const currentPost = row.detectionPost || ''
    if (!currentWorkplace || !currentPost) {
      row.sampleObjectLocation = [val]
      emitChange()
      return
    }
    const conflict = form.value.table.some((r: any) => {
      if (r === row) return false
      const sel = Array.isArray(r.sampleObjectLocation)
        ? r.sampleObjectLocation[0]
        : r.sampleObjectLocation
      return (
        (r.workplace || '') === currentWorkplace &&
        (r.detectionPost || '') === currentPost &&
        sel === val
      )
    })
    if (conflict) {
      ElMessage && ElMessage.warning('同一工作场所+检测岗位下该选项已被占用，请选择其他项')
      return
    }
  }
  row.sampleObjectLocation = val === '' || val == null ? [] : [val]
  emitChange()
}

const defaultForm = () => ({
  taskNumber: '',
  sampleDate: '',
  company: '',
  address: '',
  collectorType: '',
  flowmeterInfo: [],
  samplingInstrumentInfo: '',
  basis: '',
  airPressure: '',
  type: '定期检测',
  item: '',
  table: [
    {
      sampleNo: '',
      workplace: '',
      detectionPost: '',
      sampleObjectLocation: [],
      sampleObjectLocationed: [],
      samplingEquipmentNo: '',
      equipmentId: '',
      equipmentName: '',
      equipmentModel: '',
      flowRate: '',
      flowBefore: '',
      flowAfter: '',
      timeRange: ['', ''],
      sampleDuration: '',
      sampleVolume: '',
      contactTime: '',
      productionStatus: '',
      protectionFacilityStatus: '',
      maskStatus: '',
      temperature: '',
      workHours: '',
      workDays: '',
      remark: '',
      logId: null
    }
  ]
})
const form = ref<any>(props.formData ? { ...defaultForm(), ...props.formData } : defaultForm())

const samplingInstrumentInfo = computed(() => {
  const mySet = new Set()
  form.value.table.forEach((row) => {
    if (row.equipmentName && row.equipmentModel) {
      mySet.add(row.equipmentName + '/' + row.equipmentModel + '/' + row.samplingEquipmentNo)
    }
  })
  return Array.from(mySet).join('，')
})

const flowmeterInfoDisplay = computed(() => {
  if (!Array.isArray(form.value.flowmeterInfo)) return ''
  return form.value.flowmeterInfo.join('，')
})

interface WeatherRecord {
  id: string
  sampleDate: string
  temperature: string
  airPressure: string
  humidity: string
}

// 监听计算属性的变化并更新表单
watch(samplingInstrumentInfo, (newVal) => {
  form.value.samplingInstrumentInfo = newVal
  emitChange()
})

// 监听formData变化，自动赋值
watch(
  () => props.formData,
  (val) => {
    if (val) {
      const defaultData = defaultForm()
      Object.assign(form.value, defaultData, val)

      if (val.table && Array.isArray(val.table)) {
        form.value.table = val.table.map((tableRow, index) => {
          const newRow = { ...defaultData.table[0], ...tableRow }

          // 保留后端返回的日志ID
          newRow.logId = tableRow.logId ?? newRow.logId ?? null

          // 处理选项和选择的数据分离
          if (Array.isArray(tableRow.sampleObjectLocation)) {
            // 如果传入的数据中有 sampleObjectLocationed 字段，直接使用
            if (Array.isArray(tableRow.sampleObjectLocationed)) {
              newRow.sampleObjectLocationed = [...tableRow.sampleObjectLocationed]
              newRow.sampleObjectLocation = [...tableRow.sampleObjectLocation]
            } else {
              // 如果没有分离字段，判断是初始化还是用户数据
              const isInitialLoad = !originalOptionsMap.value.has(index)

              if (isInitialLoad) {
                // 初始化：sampleObjectLocation包含选项列表
                newRow.sampleObjectLocationed = [...tableRow.sampleObjectLocation]
                // 设置默认选择第一个
                newRow.sampleObjectLocation =
                  tableRow.sampleObjectLocation.length > 0 ? [tableRow.sampleObjectLocation[0]] : []
              } else {
                // 用户数据：sampleObjectLocation包含用户选择
                newRow.sampleObjectLocation = [...tableRow.sampleObjectLocation]
                // 保持现有的选项不变
                const existingOptions =
                  form.value.table?.[index]?.sampleObjectLocationed ||
                  originalOptionsMap.value.get(index) ||
                  []
                newRow.sampleObjectLocationed = [...existingOptions]
              }
            }
          } else {
            newRow.sampleObjectLocation = []
            newRow.sampleObjectLocationed = []
          }

          // 计算采样体积
          newRow.sampleVolume = calculateSampleVolume(newRow)

          return newRow
        })
        // 为空选择的行按唯一规则分配默认选项
        ensureUniqueDefaultSelection()
      } else {
        form.value.table = defaultData.table
      }
    }
  },
  { immediate: true }
)

watch(
  () => props.type,
  (val) => {
    if (val) {
      if (props.type === 'fix') {
        label.value = '采样点及时机'
      } else {
        label.value = '采样对象'
      }
    }
  },
  { immediate: true }
)

watch(
  () => props.weatherRecords,
  (val) => {
    if (val) {
      form.value.airPressure = val.airPressure
      form.value.sampleDate = val.sampleDate
      form.value.table.forEach((item) => {
        item.temperature = val.temperature
      })
    }
  },
  { immediate: true }
)

const addRow = () => {
  const newRow = {
    sampleNo: '',
    workplace: '',
    detectionPost: '',
    sampleObjectLocation: [],
    sampleObjectLocationed: [],
    samplingEquipmentNo: '',
    equipmentId: '',
    equipmentName: '',
    equipmentModel: '',
    flowRate: '',
    flowBefore: '',
    flowAfter: '',
    timeRange: ['', ''],
    sampleDuration: '',
    sampleVolume: '',
    contactTime: '',
    productionStatus: '',
    protectionFacilityStatus: '',
    maskStatus: '',
    temperature: '',
    remark: '',
    logId: null
  }

  // 计算采样体积
  newRow.sampleVolume = calculateSampleVolume(newRow)

  form.value.table.push(newRow)
}
// 双击打开设备选择弹窗
const getCllmbhList = async () => {
  const projectId = route.query.projectId as string
  const result = await ProjectApi.getBeforeSample(Number(projectId))
  const hasTabled = result.hasOwnProperty('tabled')
  // 当没有被选择字段的时候也就是从来都没有被选过 那么就返回所有数据
  if (!hasTabled) {
    cllmbhList.value = result.table.map((item) => item.cllmbh).sort((a, b) => a - b)
  } else {
    cllmbhList.value = result.tabled.map((item) => item).sort((a, b) => a - b)
  }
  console.log('1', JSON.stringify(cllmbhList.value))
}
// 同步滤膜id的变化
const updateBeforeSampleLM = async () => {
  await ProjectApi.updateBeforeSampleLM({
    projectId: route.query.projectId,
    add: add.value,
    remove: remove.value
  })
}

// 备注选择聚焦时，缓存当前值用于之后计算 add/remove
const onRemarkFocus = (rowIndex: number, row: any) => {
  previousRemarkMap.value.set(rowIndex, row?.remark || '')
}

// 备注变更时，计算 add/remove 并调用保存
const handleRemarkChange = async (newValue: string, rowIndex: number) => {
  const previousValue = previousRemarkMap.value.get(rowIndex) || ''
  add.value = newValue || ''
  remove.value = previousValue && previousValue !== newValue ? previousValue : ''
  await updateBeforeSampleLM()
  previousRemarkMap.value.set(rowIndex, newValue || '')
  emitChange()
}

// 双击打开设备选择弹窗
const openFacilityDialog = (index: number) => {
  currentRowIndex.value = index
  facilityDialogContext.value = { type: 'table', rowIndex: index }
  facilityShowSelection.value = false
  instrumentType.value = ''
  facilityDialogVisible.value = true
}
const openFlowmeterDialog = () => {
  facilityDialogContext.value = { type: 'flowmeter' }
  facilityShowSelection.value = true
  instrumentType.value = 'llj'
  selectedFlowmeters.value = []
  facilityDialogVisible.value = true
}
const handleFacilitySelectionChange = (selection: any[]) => {
  if (facilityDialogContext.value?.type === 'flowmeter') {
    selectedFlowmeters.value = Array.isArray(selection) ? selection : []
  } else {
    const facility = Array.isArray(selection[0]) ? selection[0][0] : selection[0]
    selectedFacility.value = facility || null
  }
}
const handleFacilityConfirm = async () => {
  if (facilityDialogContext.value?.type === 'flowmeter') {
    if (selectedFlowmeters.value.length === 0) {
      ElMessage.warning('请选择流量计')
      return
    }
    const labels: string[] = selectedFlowmeters.value.map((fm: any) => {
      const name = fm?.name || ''
      const model = fm?.model || ''
      const sn = fm?.serialNumber || ''
      return `${name}/${model}/${sn}`
    })
    form.value.flowmeterInfo = labels
    facilityDialogVisible.value = false
    selectedFlowmeters.value = []
    facilityDialogContext.value = null
    ElMessage.success('选择流量计成功')
    emitChange()
  } else if (currentRowIndex.value !== null && selectedFacility.value) {
    const row = form.value.table[currentRowIndex.value]
    const equipmentId = selectedFacility.value.id || ''
    const [startTime, endTime] = row.timeRange || ['', '']

    // 如果有时间范围，检查设备可用性
    if (startTime && endTime && injectedCheckEquipmentAvailability) {
      const newId = await injectedCheckEquipmentAvailability({
        equipmentId,
        startTime,
        endTime,
        sampleDate: form.value.sampleDate,
        currentLogId: row.logId,
        sampleNo: row.sampleNo || ''
      })
      if (newId) row.logId = newId
    }

    // 设备可用，设置设备信息
    row.samplingEquipmentNo = selectedFacility.value.serialNumber || ''
    row.equipmentId = equipmentId
    row.equipmentName = selectedFacility.value.name || ''
    row.equipmentModel = selectedFacility.value.model || ''
    row.flowRate = selectedFacility.value.flowRate || ''

    facilityDialogVisible.value = false
    selectedFacility.value = null
    currentRowIndex.value = null
    facilityDialogContext.value = null
    ElMessage.success('选择设备成功')
    emitChange()
  } else {
    ElMessage.warning('请选择设备')
  }
}



// 校验本表单必填项不为空；供父组件调用
const validateRequired = (): boolean => {
  console.log('form.value',JSON.stringify(form.value))
  // 头部表单必填项
  const headerEmpty: string[] = []
  if (!form.value.sampleDate) headerEmpty.push('采样日期')
  if (form.value.airPressure === '') headerEmpty.push('气压')
  if (!form.value.collectorType) headerEmpty.push('收集器种类')
  if (!form.value.type) headerEmpty.push('检测类别')
  if (!form.value.item) headerEmpty.push('检测项目')
  if (!form.value.basis) headerEmpty.push('采样依据')
  if (!form.value.samplingInstrumentInfo) headerEmpty.push('采样仪器信息')
  if (form.value.flowmeterInfo.length ===0) headerEmpty.push('流量计信息')
  if (headerEmpty.length > 0) {
    ElMessage && ElMessage.warning("【"+props.labelName+"】"+"【"+form.value.item+"】"+`—未填写：${headerEmpty.join('、')}`)
    return false
  }

  // 表格必填项
  const fieldLabels: Record<string, string> = {
    sampleNo: '采样编号',
    workplace: '工作场所',
    detectionPost: '检测岗位',
    sampleObjectLocation: label.value,
    samplingEquipmentNo: '采样设备编号',
    flowBefore: '采样前流量',
    flowAfter: '采样后流量',
    timeRange: '采样起止时间',
    sampleDuration: '采样时长',
    contactTime: '代表接触时间',
    remark: '粉尘滤膜编号',
    temperature: '气温'
  }

  for (let i = 0; i < form.value.table.length; i++) {
    const row = form.value.table[i]
    console.log('2121222', JSON.stringify(row))
    const emptyFields: string[] = []

    if (!row.sampleNo) emptyFields.push(fieldLabels.sampleNo)
    if (!row.workplace) emptyFields.push(fieldLabels.workplace)
    if (!row.detectionPost) emptyFields.push(fieldLabels.detectionPost)
    const singleLocation = Array.isArray(row.sampleObjectLocation)
      ? (row.sampleObjectLocation[0] || '')
      : (row.sampleObjectLocation || '')
    if (!singleLocation) emptyFields.push(fieldLabels.sampleObjectLocation)
    if (!row.samplingEquipmentNo) emptyFields.push(fieldLabels.samplingEquipmentNo)
    if (row.flowBefore === ''||row.flowBefore==0) emptyFields.push(fieldLabels.flowBefore)
    if (row.flowAfter === ''||row.flowBefore==0) emptyFields.push(fieldLabels.flowAfter)

    const [start, end] = Array.isArray(row.timeRange) ? row.timeRange : ['', '']
    if (!start || !end) emptyFields.push(fieldLabels.timeRange)
    if (row.sampleDuration === '') emptyFields.push(fieldLabels.sampleDuration)
    if (row.contactTime === '') emptyFields.push(fieldLabels.contactTime)
    if (row.temperature === '') emptyFields.push(fieldLabels.temperature)
    if (row.remark === '') emptyFields.push(fieldLabels.remark)

    if (emptyFields.length > 0) {
      ElMessage && ElMessage.warning("【"+props.labelName+"】"+"【"+form.value.item+"】"+"【"+row.sampleNo+"】"+`—未填写：${emptyFields.join('、')}`)
      return false
    }
  }

  return true
}

// 暴露数据给父组件
defineExpose({
  form,
  addRow,
  openFacilityDialog,
  openFlowmeterDialog,
  handleFacilitySelectionChange,
  handleFacilityConfirm,
  validateRequired
})

onMounted(async () => {
})
</script>

<style lang="scss" scoped>
.chem-title {
  font-size: 26px;
  font-weight: 600;
  color: #222;
  flex-grow: 1;
  text-align: center;
}

.chem-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 0 24px 0;
  padding: 16px 0 16px 0;
  border-bottom: 1.5px solid #409eff;
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
  background: none;
  border-radius: 0;
  box-shadow: none;
  letter-spacing: 1px;
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;

  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  // 设置表格行高
  :deep(.el-table__body td) {
    border-radius: 0 !important;

    font-size: 14px;
    padding: 0 !important;
    // 列和单元格的边距
    .cell {
      padding: 0px 0px;
    }
  }

  // 去掉输入框边框
  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}

.input-with-unit {
  position: relative;
}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}
</style>
